package com.example.library_base.base

import android.os.Bundle
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.annotation.NonNull
import androidx.core.util.forEach
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.trello.rxlifecycle3.components.support.RxFragment

abstract class BaseFragment<M : BaseModel, VM : BaseViewModel<M>>(@LayoutRes val layoutId: Int)
    : RxFragment() {

    private var mBinding: ViewDataBinding? = null
    private lateinit var variables: SparseArray<Any>
    protected lateinit var mViewModel: VM

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initData()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        //初始化DataBinding与ViewModel的绑定
        mBinding = DataBindingUtil.inflate(inflater, layoutId, container, false)
        return mBinding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViewModelBinding()
    }

    private fun initViewModelBinding(){
        mViewModel = getViewModel()

        variables = getVariableSparseArray()

        variables.forEach { key, value ->
            mBinding?.setVariable(key, value)
        }

        //支持LiveDate绑定XML，数据改变，UI自动更新
        mBinding?.lifecycleOwner = this
    }

    override fun onDestroy() {
        super.onDestroy()
        mBinding?.unbind()
    }

    //刷新布局
    protected fun refreshLayout(){
        variables.forEach { key, value ->
            mBinding?.setVariable(key, value)
        }
    }

    protected fun createViewModel(@NonNull cls: Class<VM>, @NonNull factory: ViewModelProvider.NewInstanceFactory): VM{
        return ViewModelProvider(this, factory).get(cls)
    }

    protected fun <T: BaseEventHandler> createEventHandler(@NonNull cls: Class<T>): T{
        return cls.newInstance()
    }

    //初始化ViewModel
    protected abstract fun getViewModel(): VM

    //绑定布局与Model
    protected abstract fun getVariableSparseArray(): SparseArray<Any>

    //初始化点击事件
    protected abstract fun getEventHandler(): BaseEventHandler

    //初始化页面数据
    protected abstract fun initData()

    //进行网络请求
    protected abstract fun requestData()
}